package com.concurrent.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;

public class TwinsLock implements Lock{

    private final Sync sync = new Sync(2);

    public void lock() {
        sync.acquireShared(1);
    }

    public void lockInterruptibly() throws InterruptedException {

    }

    public boolean tryLock() {
        return false;
    }

    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    public void unlock() {
        sync.releaseShared(1);
    }

    public Condition newCondition() {
        return null;
    }

    private static final class Sync extends AbstractQueuedSynchronizer{
        Sync(int count){
            if(count<=0){
                throw new IllegalArgumentException("count must large then zero.");
            }
            setState(count);
        }

        @Override
        protected int tryAcquireShared(int reduceCount) {
            for(;;){
                int current = getState();
                int newCount = current - reduceCount;
                if(compareAndSetState(current,newCount)){
                    return newCount;
                }
            }
        }

        @Override
        protected boolean tryReleaseShared(int returnCount) {
            for(;;){
                int current = getState();
                int newCount = current + returnCount;
                if(compareAndSetState(newCount,returnCount)){
                    return true;
                }
            }
        }
    }
    public static void main(String[] args){
        final Lock lock = new TwinsLock();
        class Worker extends Thread{
            public void run() {
                while(true){
                    lock.lock();
                    try{
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName());
                        Thread.sleep(1000);
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }
        }
        for(int i=0;i<10;i++){
            Worker worker = new Worker();
            worker.setDaemon(true);
            worker.start();
        }
        for(int i=0;i<10;i++){
            try {
                Thread.sleep(1000);
                System.out.println("-----------------");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
